package com.itshizhan.demo01.result.result;

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;

import java.io.Serializable;
import java.util.Calendar;

@JsonInclude(JsonInclude.Include.NON_NULL)
@Data
public class Result<T> implements Serializable {
	private Integer code;
	private String msg;
	private Long timestamp;
	private T data;


	public Result(Integer code, String msg) {
		this.code = code;
		this.msg = msg;
		this.timestamp = timestamp();
	}

	public Result(Integer code, String msg, T data) {
		this.code = code;
		this.msg = msg;
		this.data = data;
		this.timestamp = timestamp();
	}


	private Long timestamp() {
		return Calendar.getInstance().getTimeInMillis();
	}

	// 成功，不需要返回数据
	public static <T> Result<T> success(){
		return new Result<T>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg());
	}

	// 成功，返回数据
	public static <T> Result<T> success(T data){
		return new Result<T>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), data);
	}


	//错误，不需要告知原因 和 错误码
	public static <T> Result<T> fail(){
		return new Result<T>(ResultEnum.Fail.getCode(), ResultEnum.Fail.getMsg());
	}
	//错误，告知原因
	public static <T> Result<T> fail(String msg) {
		return new Result<T>(ResultEnum.Fail.getCode(), msg);
	}
	//错误，告知原因 和 错误码
	public static <T> Result<T> fail(ResultEnum resultEnum){
		return new Result<T>(resultEnum.getCode(), resultEnum.getMsg());
	}
	//错误，告知原因 和 错误码 和 错误数据
	public static <T> Result<T> fail(ResultEnum resultEnum,T data){
		return new Result<T>(resultEnum.getCode(), resultEnum.getMsg(),data);
	}


	public static void main(String[] args) {
		System.out.println(Result.success());
		System.out.println(Result.success("[1,2,3]"));
		System.out.println(Result.fail());
		System.out.println(Result.fail("服务异常"));
		System.out.println(Result.fail(ResultEnum.ERROR_PARAMETER));
	}
}
